/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bundle;

import entities.CandidateType;
import entities.CandidateTypeDescription;
import java.io.IOException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.ResourceBundle.Control;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 *
 * @author Alvaro
 */
public class CandidateTypeBundle extends ResourceBundle {
    
    private static final EntityManagerFactory factory = Persistence.createEntityManagerFactory("ProyectoPU");
    private static final EntityManager em = factory.createEntityManager();

    protected static final String BASE_NAME = "CandidateType.findAll";
    protected static final Control DB_CONTROL = new DBControl();

    private Map<String, String> messages;

    public CandidateTypeBundle() {
        setParent(ResourceBundle.getBundle(BASE_NAME, 
            FacesContext.getCurrentInstance().getViewRoot().getLocale(), DB_CONTROL));
    }

    protected CandidateTypeBundle(Map<String, String> messages) {
        this.messages = messages;
    }

    @Override
    protected Object handleGetObject(String key) {
        return messages != null ? messages.get(key) : parent.getObject(key);
    }

    @Override
    public Enumeration<String> getKeys() {
        return messages != null ? Collections.enumeration(messages.keySet()) : parent.getKeys();
    }

    protected static class DBControl extends Control {

        @Override
        public ResourceBundle newBundle
            (String baseName, Locale locale, String format, ClassLoader loader, boolean reload)
                throws IllegalAccessException, InstantiationException, IOException
        {
            String language = locale.getLanguage();
            Map<String, String> messages= new HashMap<String, String>();
            List<CandidateType> candidateType=em.createNamedQuery(baseName).getResultList();
            for (CandidateType canTy : candidateType) {
                String description=canTy.getDescription();
                for(CandidateTypeDescription cd: canTy.getCandidateTypeDescriptionList()){
                    if(cd.getLanguage().getCode().equalsIgnoreCase(language)){
                        description=cd.getDescription();
                        break;
                    }
                }
                 messages.put(canTy.getIdCandidateType().toString(), description);
            }
            return new CandidateTypeBundle(messages);
        }

    }

}